package com.tangula.web.config.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import com.tangula.core.Logging;
import com.tangula.web.kashine.controller.AuthController;
import com.tangula.web.kashine.repository.AccountEntityRepository;

@Service
public class KashineInterceptor implements HandlerInterceptor {

	@Autowired
	private AccountEntityRepository repo;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String userid = request.getHeader("auth");
		Logging.findLoggerByClass(KashineInterceptor.class).debug("http request uri:"+request.getRequestURI());
		Logging.findLoggerByClass(KashineInterceptor.class).debug("http header auth:"+userid);
		if(StringUtils.isNotBlank(userid)) {
			AuthController.ACCOUNT_LOCAL.set(repo.findById(userid).orElseGet(()->null));
		}else {
			AuthController.ACCOUNT_LOCAL.set(null);
		}
		return true;
	}
}
